package com.bugmonkey.example;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.bugmonkey.cameraviewx.camera.CameraViewActivity;
import com.bugmonkey.cameraviewx.camera.ImagePreviewActivity;
import com.bugmonkey.cameraviewx.watermark.OnBitmapGeneratedCallback;
import com.bugmonkey.example.databinding.ActivityMainBinding;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {


    private ActivityMainBinding binding;

    public static void start(Context context,Uri uri) {
        Intent starter = new Intent(context, MainActivity.class);
        starter.putExtra(ImagePreviewActivity.RESULT_URI,uri);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Glide.with(this).asBitmap().load((Uri) getIntent().getParcelableExtra(ImagePreviewActivity.RESULT_URI)).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                binding.parent.setImageViewBitmap(createIdealRatioBitmap(resource,3.0f/4,9.0f / 16));
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {

            }
        })
        ;

        binding.btnExportBitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 binding.watermarkContainer.exportWaterMarkBitmap(new OnBitmapGeneratedCallback() {
                     @Override
                     public void onBitmapGenerated(Bitmap bitmap) {
                         if(bitmap!=null){
                             MainActivity2.start(MainActivity.this,saveBitmap(""+System.currentTimeMillis(),bitmap,MainActivity.this));
                         }
                     }
                 });



            }
        });

        binding.btnRetake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraViewActivity.start(MainActivity.this);
            }
        });

    }

    /**
     * 创建符合理想宽高比的bitmap
     * @param originalBmp
     * @param maxRatio 现在最大宽高比，小于就使用新的宽高比
     * @param newRatio
     * @return
     */
    public  Bitmap createIdealRatioBitmap(Bitmap originalBmp,float maxRatio,float newRatio){
        float oldRatio = originalBmp.getWidth()*1f/originalBmp.getHeight();
        if (oldRatio <= maxRatio){
            return originalBmp;
        }else {
            int width = getResources().getDisplayMetrics().widthPixels;
            Bitmap resizedBmp = Bitmap.createScaledBitmap(originalBmp,width,(width*originalBmp.getHeight()/originalBmp.getWidth()),true);
//            originalBmp.recycle();
            Bitmap newBitmap = Bitmap.createBitmap(width, (int) (width/newRatio),resizedBmp.getConfig());
            Paint paint = new Paint();
            paint.setColor(0x000000);
            Canvas canvas = new Canvas(newBitmap);
            canvas.drawRect(0,0,newBitmap.getWidth(),newBitmap.getHeight(),paint);
            canvas.drawBitmap(resizedBmp,0,(newBitmap.getHeight()-resizedBmp.getHeight())*1f/2,null);


            return newBitmap;
        }
    }

    private String saveBitmap(String name, Bitmap bm, Context mContext) {

        Log.d("Save Bitmap", "Ready to save picture");

        //指定我们想要存储文件的地址

        String TargetPath = mContext.getFilesDir() + "/images/";

        Log.d("Save Bitmap", "Save Path=" + TargetPath);

        File file = new File(TargetPath);

        //判断指定文件夹的路径是否存在

        if (!file.exists()) {
            file.mkdirs();
            Log.d("Save Bitmap", "TargetPath isn't exist");

        }


            //如果指定文件夹创建成功，那么我们则需要进行图片存储操作

            File saveFile = new File(TargetPath, name);



            try {

                FileOutputStream saveImgOut = new FileOutputStream(saveFile);

                // compress - 压缩的意思

                bm.compress(Bitmap.CompressFormat.JPEG, 80, saveImgOut);

                //存储完成后需要清除相关的进程

                saveImgOut.flush();

                saveImgOut.close();

                Log.d("Save Bitmap", "The picture is save to your phone!");

            } catch (IOException ex) {

                ex.printStackTrace();

            }


        return  saveFile.getAbsolutePath();
    }


}